package org.jeecg.modules.sms.sms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.sms.sms.entity.CsSmsCzjl;
import org.jeecg.modules.sms.sms.mapper.CsSmsCzjlMapper;
import org.jeecg.modules.sms.sms.service.ICsSmsCzjlService;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @Description: 短信充值记录表
 * @Author: jeecg-boot
 * @Date:   2023-11-08
 * @Version: V1.0
 */
@Service
public class CsSmsCzjlServiceImpl extends ServiceImpl<CsSmsCzjlMapper, CsSmsCzjl> implements ICsSmsCzjlService {

    @Override
    public boolean checkSmsYe(String tenantId, int fsts) {
        int syts = this.baseMapper.getSmsYe(tenantId);
        if(syts > 0 && syts >= fsts) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public Result<String> reduceSmsYe(String tenantId, int reduceCount) {
        //cwgx todo:加锁
        try {
            if (!checkSmsYe(tenantId, reduceCount)) {
                return Result.error("余额不足");
            }
            //从日期最早的开始扣减
            List<CsSmsCzjl> list = this.lambdaQuery().eq(CsSmsCzjl::getTenantId, tenantId).eq(CsSmsCzjl::getYxzt, "1").orderByAsc(CsSmsCzjl::getCreateTime).list();

            for (CsSmsCzjl csSmsCzjl : list) {
                if (csSmsCzjl.getSyts() >= reduceCount) { //当前的记录可以扣减完
                    int syts = csSmsCzjl.getSyts() - reduceCount;
                    csSmsCzjl.setSyts(syts);
                    if (syts <= 0) {
                        csSmsCzjl.setYxzt("0");
                    }
                    this.updateById(csSmsCzjl);
                    reduceCount = 0;
                    //扣减完，退出循环
                    break;
                } else if (csSmsCzjl.getSyts() > 0 && csSmsCzjl.getSyts() < reduceCount) {//部分扣减
                    reduceCount = reduceCount - csSmsCzjl.getSyts();
                    csSmsCzjl.setSyts(0);
                    csSmsCzjl.setYxzt("0");
                    this.updateById(csSmsCzjl);
                } else if (csSmsCzjl.getSyts() <= 0) {//剩余数量小于0 置为无效状态
                    csSmsCzjl.setYxzt("0");
                    this.updateById(csSmsCzjl);
                }
            }

            //所有记录扣减完仍未扣减完，报余额不足错误
            if (reduceCount > 0) {
                //throw new JeecgBootException("余额不足");
                //因短信已发出，能扣减得不在抛异常回滚
                return Result.error("余额不足");
            }
        } finally {
            //cwgx todo:解锁
        }
        return Result.OK("成功");
    }
}
